package com.samsung.sbackup;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.samsung.handler.CalendarHandler;
import com.samsung.handler.ContactHandler;
import com.samsung.handler.SmsHandler;
import com.samsung.handler.ZipHandler;

public class AlarmReceiver extends BroadcastReceiver {
	SharedPreferences sharedPref;
	ArrayList<String> list = new ArrayList<String>();
	ContactThread contactThread;
	CalendarThread calendarThread;
	CalendarHandler calendar;
	SmsThread smsThread;
	ContactHandler contact;
	SmsHandler sms;
	int count = 0;
	int checkDuplicate;
	Context ctx;
	Editor prefEditor;
	String lastTask;
	
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		ctx = arg0;
		sharedPref = PreferenceManager.getDefaultSharedPreferences(arg0
				.getApplicationContext());
		prefEditor = sharedPref.edit();
		String listTask = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_OPTIONS, "1110");
		String folder = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_PATH, "/");
		int maxBackups = Integer.parseInt(sharedPref.getString(
				FragmentSettingsPreference.MAX_BACKUPS, "5"));
		SimpleDateFormat sf = new SimpleDateFormat("HH.mm dd-MM-yyyy",
				Locale.getDefault());
		File f = new File(folder);
		MainActivity.createFolder(folder, arg0);
		
		if (f.exists()) {
			String date = sf.format(Calendar.getInstance().getTime());
			 String currentBackups = "";
			list.clear();

			if (listTask.charAt(0) == '1') {
				list.add("contact");
				currentBackups += "contact ";
			}
			if (listTask.charAt(1) == '1') {
				list.add("sms");
				currentBackups += "sms ";
			}
			if (listTask.charAt(2) == '1') {
				list.add("calendar");
				currentBackups += "calendar ";
			}
			if (listTask.charAt(3) == '1') {
				list.add("app");
				currentBackups += "app ";
			}
			
			QuickBackup.MaxBackupsChecker(currentBackups, maxBackups, folder);
			
			if (list.size() != 0
					&& sharedPref.getBoolean(
							FragmentSettingsPreference.SCHEDULE_BACKUP, false) == true) {
				long tomorrow = Calendar.getInstance().getTimeInMillis()
						+ Long.valueOf(sharedPref.getInt(
								FragmentSettingsPreference.REPEATATION, 1))
						* 1000 * 24 * 3600;
				prefEditor.putString(FragmentSettingsPreference.BACKUP_TIME,
						ConvertToDate(tomorrow));
				prefEditor.commit();
				{
					for (int i = 0; i < list.size(); i++) {

						lastTask = list.get(list.size()-1);
						if (list.get(i).equals("calendar")) {
							for (File s : f.listFiles()) {
								if (s.getName().equals(
										"calendar_" + date + ".zip")) {
									s.delete();
								}
							}

							calendar = new CalendarHandler(arg0);
							calendarThread = new CalendarThread(date);
							calendarThread.start();

						} else if (list.get(i).equals("contact")) {
							for (File s : f.listFiles()) {
								if (s.getName().equals(
										"contact_" + date + ".zip")) {
									s.delete();
								}
							}

							contact = new ContactHandler(arg0);

							contactThread = new ContactThread(date);
							contactThread.start();
							Log.e("", "contact");

						} else if (list.get(i).equals("sms")) {
							for (File s : f.listFiles()) {
								if (s.getName().equals("sms" + date + ".zip")) {
									s.delete();
								}

							}

							sms = new SmsHandler(arg0);
							smsThread = new SmsThread(date);
							smsThread.start();
							Log.e("", "sms");

						} else if (list.get(i).equals("app")) {

							new BackupApps().execute();
						}
					}
					count = 0;
				}

			}
		}
	}

	public class ContactThread extends Thread {
		public ContactThread(String str) {
			contact.setFile(sharedPref.getString(
					FragmentSettingsPreference.BACKUP_PATH, "/")
					+ "/contact_"
					+ str + ".vcf");
		}

		@Override
		public void run() {

			contact.backup();

			ZipHandler.zipCompress(
					contact.getFile().substring(0,
							contact.getFile().lastIndexOf("/")),
					contact.getFile(), null);

			File f = new File(contact.getFile());
			f.delete();
			if(lastTask.equals("contact")){
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						ctx).setSmallIcon(R.drawable.ic_launcher)
						.setContentTitle("SBackup").setContentText("Schedule back up finised.")
						.setAutoCancel(true);

				Intent resultIntent = new Intent(ctx, ScheduleSettings.class);
				PendingIntent resultPendingIntent = PendingIntent.getActivity(ctx,
						0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_ONE_SHOT);
				mBuilder.setContentIntent(resultPendingIntent);
				int mNotificationId = 001;
				NotificationManager mNotifyMgr = (NotificationManager) ctx
						.getSystemService(Context.NOTIFICATION_SERVICE);
				mNotifyMgr.notify(mNotificationId, mBuilder.build());
			}
		}
	}

	public class SmsThread extends Thread {
		public SmsThread(String str) {
			sms.setFile(sharedPref.getString(
					FragmentSettingsPreference.BACKUP_PATH, "/")
					+ "/sms_"
					+ str + ".xml");
		}

		@Override
		public void run() {
			{
				try {
					contactThread.join();
				} catch (Exception e) {
					e.printStackTrace();
				}
				sms.backup(ctx.getContentResolver());

				ZipHandler.zipCompress(
						sms.getFile().substring(0,
								sms.getFile().lastIndexOf("/")), sms.getFile(),
						null);

				File f = new File(sms.getFile());
				f.delete();
				if(lastTask.equals("sms")){
					NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
							ctx).setSmallIcon(R.drawable.ic_launcher)
							.setContentTitle("SBackup").setContentText("Schedule back up finised.")
							.setAutoCancel(true);

					Intent resultIntent = new Intent(ctx, ScheduleSettings.class);
					PendingIntent resultPendingIntent = PendingIntent.getActivity(ctx,
							0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_ONE_SHOT);
					mBuilder.setContentIntent(resultPendingIntent);
					int mNotificationId = 001;
					NotificationManager mNotifyMgr = (NotificationManager) ctx
							.getSystemService(Context.NOTIFICATION_SERVICE);
					mNotifyMgr.notify(mNotificationId, mBuilder.build());
				}
			}
		}
	}

	public class CalendarThread extends Thread {
		public CalendarThread(String str) {
			calendar.setFile(sharedPref.getString(
					FragmentSettingsPreference.BACKUP_PATH, "/")
					+ "/calendar_"
					+ str + ".xml");
		}

		@Override
		public void run() {
			try {
				contactThread.join();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				smsThread.join();
			} catch (Exception e) {
				e.printStackTrace();
			}

			calendar.backup();

			ZipHandler.zipCompress(
					calendar.getFile().substring(0,
							calendar.getFile().lastIndexOf("/")),
					calendar.getFile(), null);

			File f = new File(calendar.getFile());
			f.delete();
			if(lastTask.equals("calendar")){
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						ctx).setSmallIcon(R.drawable.ic_launcher)
						.setContentTitle("SBackup").setContentText("Schedule back up finised.")
						.setAutoCancel(true);

				Intent resultIntent = new Intent(ctx, ScheduleSettings.class);
				PendingIntent resultPendingIntent = PendingIntent.getActivity(ctx,
						0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_ONE_SHOT);
				mBuilder.setContentIntent(resultPendingIntent);
				int mNotificationId = 001;
				NotificationManager mNotifyMgr = (NotificationManager) ctx
						.getSystemService(Context.NOTIFICATION_SERVICE);
				mNotifyMgr.notify(mNotificationId, mBuilder.build());
			}
			
		}
	}

	public class BackupApps extends AsyncTask<Void, Integer, String> {
		// ProgressDialog progressDialog;
		ArrayList<ApplicationInfo> appsList;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// get all application infos
			ArrayList<ApplicationInfo> infos = (ArrayList<ApplicationInfo>) ctx
					.getPackageManager().getInstalledApplications(
							PackageManager.GET_META_DATA);
			appsList = new ArrayList<ApplicationInfo>();
			for (ApplicationInfo applicationInfo : infos) {
				if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
					appsList.add(applicationInfo);
			}
		}

		@Override
		protected String doInBackground(Void... params) {
			int count = 0;
			for (ApplicationInfo item : appsList) {
				try {
					File f1 = new File(item.publicSourceDir);

					String path = sharedPref.getString(
							FragmentSettingsPreference.BACKUP_PATH, "/");

					File f2 = new File(path + "/" + "app");
					f2.mkdirs();
					f2 = new File(f2.getPath() + "/"
							+ item.loadLabel(ctx.getPackageManager()) + ".apk");
					f2.createNewFile();
					InputStream in = new FileInputStream(f1);

					OutputStream out = new FileOutputStream(f2);

					byte[] buf = new byte[1024];
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					in.close();
					out.close();
					System.out.println("File copied.");
				} catch (FileNotFoundException ex) {
					ex.printStackTrace();
					System.out.println(ex.getMessage()
							+ " in the specified directory.");
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println(e.getMessage());
				}
				count++;
				publishProgress(count);
			}

			if (appsList.size() != 0)
				return "Done backing up applications";
			else
				return "There is no application installed";
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(lastTask.equals("app")){
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						ctx).setSmallIcon(R.drawable.ic_launcher)
						.setContentTitle("SBackup").setContentText("Schedule back up finised.")
						.setAutoCancel(true);

				Intent resultIntent = new Intent(ctx, ScheduleSettings.class);
				PendingIntent resultPendingIntent = PendingIntent.getActivity(ctx,
						0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_ONE_SHOT);
				mBuilder.setContentIntent(resultPendingIntent);
				int mNotificationId = 001;
				NotificationManager mNotifyMgr = (NotificationManager) ctx
						.getSystemService(Context.NOTIFICATION_SERVICE);
				mNotifyMgr.notify(mNotificationId, mBuilder.build());
			}
			Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
		}
	}

	public String ConvertToDate(long milisecond) {
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm",
				Locale.getDefault());
		return formatter.format(milisecond);
	}

	public String Convert(String string) {
		String input = string;
		Date date = null;
		try {
			date = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.getDefault())
					.parse(input);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long milliseconds = date.getTime();
		return String.valueOf(milliseconds);
	}
}
